import { DevSpec, PickFunDeviceModel, PickFunVersion } from "./store";

export function extractSn(qr: string): string | null {
  const match = qr.match(/sn?=(\w+)/);
  if (match) {
    return match[1];
  }
  return null;
}

export function parseQrCodeString(qr: string): DevSpec | null {
  let v = PickFunVersion.oversea;
  let m = PickFunDeviceModel.p1;
  if (qr.includes("pick-fun.com.cn")) {
    v = PickFunVersion.china;
  } else if (qr.includes("pick-fun.com")) {
    v = PickFunVersion.oversea;
  } else {
    return null;
  }

  if (qr.includes("m=0")) {
    m = PickFunDeviceModel.p0;
  } else if (qr.includes("m=3")) {
    m = PickFunDeviceModel.p3;
  } else if (qr.includes("m=a3")) {
    m = PickFunDeviceModel.a3;
  } else {
    m = PickFunDeviceModel.p1;
  }
  const sn = extractSn(qr);
  return { ver: v, model: m, sn: sn };
}

//get a string description of the devSpec
export function getDevSpecDescription(devSpec: DevSpec | null): string {
  if (!devSpec) {
    return "未知设备(无法识别二维码)";
  }
  let verStr = devSpec.ver === PickFunVersion.china ? "大陆版" : "国际版";
  let modelStr = "";
  switch (devSpec.model) {
    case PickFunDeviceModel.p0:
      modelStr = "P0";
      break;
    case PickFunDeviceModel.p3:
      modelStr = "猫砂盆";
      break;
    case PickFunDeviceModel.a3:
      modelStr = "A3";
      break;
    default:
      modelStr = "P1";
      break;
  }
  let str = `${verStr} ${modelStr}`;
  if (devSpec.sn) {
    str += ` SN:${devSpec.sn}`;
  }
  return str;
}
